<?php

namespace App\Kuafu\WaiMai\Model\Clickhouse;

use App\Kuafu\Base\Model\Traits\KfSplitRelation;
use App\Kuafu\Base\Model\Traits\KfWaiMaiSplit;
use App\Kuafu\Mybank\Service\CalcBrokerage\MybankCalcWaimaiBrokerageService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderOperateRecordModel;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Model\WaiMaiPartRefundLogModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Kuafu\LaravelClickHouse\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WaiMaiOrderCHModel extends Model
{
    protected $connection = 'clickhouseWaimaiOrderAll';
    protected $table      = 'kf_waimai_orders'; //表名
    protected $primaryKey = 'orderId';

    public function shopRel(): Relation
    {
        return $this->hasOne(Shop::class, 'id', 'shopId');
    }


    // 仅关联菜品，不关联包装物
    public function orderDetailsRel(): Relation
    {
        return $this->hasMany(WaiMaiOrderDetailCHModel::class, 'orderId', 'orderId')
                    ->where('productType', WaiMaiOrderDetailModel::PRODUCT_TYPE_1)
                    ->orderBy('originalPrice');

    }

    // 关联所有菜+包装物
    public function orderDetailsRelTotal(): Relation
    {
        return $this->hasMany(WaiMaiOrderDetailCHModel::class, 'orderId', 'orderId')
                    ->orderBy('originalPrice');
    }

    /**
     * 部分退款日志
     * @return Relation
     * @throws \Exception
     */
    public function partRefundRel(): Relation
    {
        return $this->hasMany(WaiMaiPartRefundLogCHModel::class, 'orderId', 'orderId')
                    ->orderByDesc('id');
    }

    public function orderOperateRecordRel()
    {
        return $this->hasMany(OrderOperateRecordModel::class, 'orderId', 'orderId');
    }

    public function getOrderStatusTextAttribute(): string
    {
        return WaiMaiDBEnum::ORDER_STATUS_TEXT[$this->orderStatus] ?? '';
    }

    public function getSourceTypeTextAttribute(): string
    {
        return CodeEnum::SOURCE_TYPES[$this->sourceType] ?? '';
    }

    public function getReceiverPrivacyPhoneArrAttribute(): array
    {
        return (array)json_decode($this->receiverPrivacyPhones, true);
    }

    public function getRefundPicArrAttribute(): array
    {
        return (array)json_decode($this->refundPic, true);
    }

    public function getPhoneCombineAttribute(): string
    {
        $arr = json_decode($this->receiverPrivacyPhones, true);
        if (!$arr) {
            return $this->receiverPhone;
        }

        if ($arr == '[]') {
            $arr = [];
        }

        $str = '';
        foreach ($arr as $v) {
            $str .= $v . ' / ';
        }

        $str = rtrim($str, ' / ');

        return $str . ' / ' . $this->receiverPhone;
    }

    public function getExpectTimeFormatAttribute(): string
    {
        $prefix = $this->expectFast ? "立即送达" : '预订单  期望 ';

        // 没时间，直接显示立即送达
        // 立即送达不加时间
        if (!$this->expectTime || $this->expectFast) {
            return $prefix;
        }

        // 预约当天
        if (date('Ymd') == date('Ymd', $this->expectTime)) {
            return $prefix . date('H:i', $this->expectTime);
        }

        // 预约今天以后
        return $prefix . date('m-d H:i', $this->expectTime);
    }

    public function getRefundStatusAttribute()
    {
        if ($this->orderStatus == WaiMaiDBEnum::ORDER_STATUS_6) {
            return WaiMaiDBEnum::REFUND_STATUS_1;
        }

        if ($this->orderStatus == WaiMaiDBEnum::ORDER_STATUS_7) {
            return WaiMaiDBEnum::REFUND_STATUS_2;
        }

        if ($this->isPartRefund == 1) {
            return WaiMaiDBEnum::REFUND_STATUS_3;
        }

        return WaiMaiDBEnum::REFUND_STATUS_0;
    }

    public function getTaxInfoAttribute(): array
    {
        if (!$this->taxpayers) {
            return [];
        }

        $arr = json_decode($this->taxpayers, true);
        if (!$arr) {
            return [];
        }

        return collect($arr)->map(function ($v, $k) {
            if (!$v) {
                return null;
            }

            return [
                'key'   => WaiMaiDBEnum::TAX_TEXT[$k] ?? '',
                'value' => $v,
            ];
        })->filter()->values()->toArray();
    }
}
